#!/bin/sh

touch -c "$2"

if [ -z "$USER" ]; then exit 0; fi

# If upgrading then force re-indexing for the current user immediately
if sudo -u $USER /usr/bin/mdimport -L 2>&1 | grep -q "$2"; then
    sudo -u $USER /usr/bin/mdimport -r "$2"
    exit 0;
fi

# Otherwise schedule re-indexing for the next time the current user logs on
JOB=uk.org.marginal.qlvideo.mdimporter
AGENT="$HOME/Library/LaunchAgents/$JOB.plist"
SCRIPT="$HOME/Library/Application Support/uk.org.marginal.qlvideo/mdimporter"

sudo -u $USER mkdir -p "`dirname "$SCRIPT"`"
sudo -u $USER /usr/bin/tee "$SCRIPT" >/dev/null <<EOF
#!/bin/bash
#
# QLVideo helper script to kick Spotlight into (re)indexing movie files
#

# Wait for Spotlight to notice the new importer
TRY=300
while [ \$((TRY -= 10)) -ne 0 ]; do
    if /usr/bin/mdimport -L 2>&1 | grep -q "$2"; then
        break;
    else
        sleep 10;
    fi;
done

# Force re-indexing
/usr/bin/mdimport -r "$2"

# Clean up
rm -f "$AGENT"
rm -f "$SCRIPT"
/bin/launchctl remove $JOB
EOF
chmod +x "$SCRIPT"

sudo -u $USER mkdir -p "`dirname "$AGENT"`"
sudo -u $USER /usr/bin/tee "$AGENT" >/dev/null <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$JOB</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>$SCRIPT</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF

# Launch immediately in case the user doesn't intend to log off any time soon
sudo -u $USER /bin/launchctl load "$AGENT"

true
